package cn.wolfcode.trip.app.controller;


import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户资源控制器
 */
@RestController
@RequestMapping("/regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ServletContext context;

    @GetMapping
    public List<Region> listAll(Integer state){
        return regionService.selectAll(state);
    }
    //获取某个地区下的攻略信息(返回json)
    @GetMapping(value = "/{regionId}/strategies",produces = "application/json;charset=utf-8")
    public PageInfo<Strategy> getStrategy(StrategyQueryObject qo) throws Exception {
        qo.setPageSize(8);
        return strategyService.list(qo);
    }

    //获取某个地区下的攻略信息(返回HTML)
    @GetMapping(value = "/{regionId}/strategies",produces = "text/html;charset=utf-8")
    public void getStrategy(StrategyQueryObject qo, HttpServletResponse response) throws Exception {
        //获取当季推荐攻略,设置状态为1但不分页
        qo.setState(Strategy.STATE_COMMENT);
        qo.setPageSize(0);
        PageInfo<Strategy> comments = strategyService.list(qo);
        //获取全部攻略,但要分页
        qo.setState(null);
        qo.setPageSize(8);
        PageInfo<Strategy> all = strategyService.list(qo);

        //创建freemarker的配置对象
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        //设置模板所在的文件夹
        configuration.setDirectoryForTemplateLoading(new File(context.getRealPath("/template")));
        //拿到具体的模板
        Template template = configuration.getTemplate("strategyTemplate.ftl","utf-8");
        //合成结果
        Map<String,Object> map = new HashMap<>();
        map.put("comments",comments);
        map.put("all",all);
        template.process(map,response.getWriter());


    }

}
